<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\admin\model;

use app\api\validate\Admin;
use app\team\model\TeamToken;
use think\Exception;
use think\Model;

class AdminUser extends Model
{
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 设置当前模型对应的完整数据表名称
    protected $name   = 'admin';
    protected $insert = ['status' => 1];

    public function getLastLoginTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public static function init()
    {
        self::beforeWrite(function ($row) {
            $changed = $row->getChangedData();
            //如果修改了用户或或密码则需要重新登录
            if (isset($changed['username']) || isset($changed['password']) || isset($changed['salt'])) {
                $row->token = '';
            }
        });
    }


    public function getLists($param){
        $map[] = ['team_name','<>',''];
        $map[] = ['status','=',1];
        $list = self::where($map)->field('id,team_name,nickname')->select();
        return ['code' => 200, 'msg' => '获取信息成功', 'data' => $list];
    }


    public function login($param)
    {
        try {
            if (!$param['username'] || !$param['password']) {
                throw new Exception("缺少参数");
            }
            $username = trim($param['username']);
            $password = trim($param['password']);
            $user = self::get(['username' => $username]);
            if (!$user) {
                throw new Exception('用户名不存在');
            }
            if ($user->password != encrypt_password($password, $user->encrypt)) {
                throw new Exception('密码不正确');
            }

            if ($user->status == 0) {
                throw new Exception('账号已被封禁，请联系管理员');
            }

            $wxUserMes['token'] = (new TeamToken())->product_token($user['id'], 1);
            $wxUserMes['uid'] = $user->id;
            return ['code' => 200, 'msg' => '获取信息成功', 'data' => $wxUserMes];

        } catch (Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    public function getUser($aid){
        $userInfo = self::where(['id' => $aid])->field('id,nickname,team_name')->select();
        return ['code' => 200, 'msg' => '获取成功','data'=>$userInfo];
    }


    public function applyHead($params){
        $validate = (new Admin());
        if (!$validate->scene('insert')->check($params)) {
            // 验证失败，输出错误信息
            return ['code' => 201, 'msg' => $validate->getError()];
        }
//        //验证验证码
//        $result = \app\common\library\Sms::check($params['phone'], $params['code']);
//        if(!$result){
//            return ['code' => 201, 'msg' =>'验证码错误'];
//        }
        //查询是否存在
        (new AdminUser())->where(['username' => $params['phone']])->delete();
        $passwordinfo       = encrypt_password($params['password']); //对密码进行处理
        $data['password'] = $passwordinfo['password'];
        $data['encrypt']  = $passwordinfo['encrypt'];
        $data['username'] = $params['phone'];
        $data['roleid'] =3;
        $data['nickname'] =$params['realname'];
        $data['last_login_ip'] =$this->getClientIp();
        $data['status'] =2; // 2申请团队，3团队通过 4拒绝通过
        $data['team_name'] = $params['team_name'];
        $data['last_login_time'] = time();
        $data['member_id'] = $params['uid'];

        if(!(new AdminUser())->insert($data)){
            return ['code' => 201, 'msg' => '申请失败，请重新尝试'];
        }

        return ['code' => 200, 'msg' => '申请成功'];
    }


    public function getHeadInfo($params){
       $member = (new AdminUser())->where(['member_id' => $params['uid']])->field('id,username as phone,team_name,nickname,status,reason')->find();
        return ['code' => 200, 'msg' => '申请成功','data' => $member];

    }

    public function getClientIp() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            // 判断是否有HTTP_CLIENT_IP这个请求头，存在优先使用
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 判断是否有HTTP_X_FORWARDED_FOR这个请求头，存在优先使用
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            // 获取REMOTE_ADDR这个服务器变量
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = '';
        }
        return $ip;
    }

    public function forgotPwd($params){
        //验证验证码
        $result = \app\common\library\Sms::check($params['phone'], $params['code']);
        if(!$result){
            return ['code' => 201, 'msg' =>'验证码错误'];
        }

        if(!$params['password']){
            return ['code' => 201, 'msg' =>'请填写密码'];
        }
        $passwordinfo = encrypt_password(trim($params['password'])); //对密码进行处理
        $data['password'] = $passwordinfo['password'];
        $data['encrypt'] = $passwordinfo['encrypt'];

        //更新代码
        if(!self::where(['username' => $params['phone']])->update($data)){
            return ['code' => 201, 'msg' =>'更改失败'];
        }
        return ['code' => 200, 'msg' =>'修改成功'];
    }

}
